<template>
  <div>
    <div>
      <BreadX level1="商品管理" level2="商品列表">
          <template v-slot:right> 添加商品 </template>
      </BreadX>
    </div>
    <el-card style="margin-top: 30px">
      <el-row>
        <el-col>
          <el-alert title="添加商品信息" type="info" center show-icon>
          </el-alert>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-steps
            :active="activeName * 1"
            finish-status="success"
            align-center
            style="margin-top: 20px"
          >
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
          </el-steps>
        </el-col>
        <el-col style="margin-top: 20px">
          <el-form :model="addGoodsForm">
            <el-tabs
              tab-position="left"
              :before-leave="beforeLeave"
              v-model="activeName"
              @tab-click="handleClick"
            >
              <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称">
                  <el-input v-model="addGoodsForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格">
                  <el-input v-model="addGoodsForm.goods_price"></el-input>
                </el-form-item>
                <el-form-item label="商品重量">
                  <el-input v-model="addGoodsForm.goods_weight"></el-input>
                </el-form-item>
                <el-form-item label="商品数量">
                  <el-input v-model="addGoodsForm.goods_number"></el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                  <span>选中的商品分类：</span>
                  <el-cascader
                    v-model="checkedCatArr"
                    :options="goodsCatedata"
                    :props="defaultProps"
                    @change="handleChange"
                  ></el-cascader>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品参数" name="1">
                <!-- 动态参数 -->
                <el-form-item
                  :label="item1.attr_name"
                  v-for="item1 in manyParams"
                  :key="item1.attr_id"
                >
                  <br />
                  <el-checkbox-group v-model="item1.attr_vals">
                    <el-checkbox
                      :label="item2"
                      v-for="(item2, index) in item1.attr_vals"
                      :key="index"
                    >
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品属性" name="2">
                <!-- 静态属性 -->
                <el-form-item
                  :label="item.attr_name"
                  v-for="item in onlyParams"
                  :key="item.attr_id"
                >
                  <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品图片" name="3">
                <!-- 上传图片 -->
                <el-upload
                  class="upload-demo"
                  action="https://www.liulongbin.top:8888/api/private/v1/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :file-list="fileList"
                  :headers="headers"
                  list-type="picture"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                     只能上传jpg/png文件，且不超过5 00kb
                  </div>
                </el-upload>
              </el-tab-pane>
              <el-tab-pane label="商品内容" name="4">
                <quill-editor v-model="addGoodsForm.goods_introduce" />
                <el-button
                  type="primary"
                  style="margin-top: 15px"
                  @click="addGoodsOk"
                  >添加商品</el-button
                >
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
import BreadX from "@/components/BreadX.vue";
export default {
  components: { BreadX },
  data() {
    return {
      // 配置上传的请求头的信息
      headers: {
        Authorization: sessionStorage.getItem("token"),
      },
      // 商品分类置顶
      defaultProps: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id",
      },
      // 已选中的商品分类数组
      checkedCatArr: [],
      // 商品分类数据源
      goodsCatedata: [],
      addGoodsForm: {
        // 商品名称
        goods_name: "",
        //以为','分割的分类列表
        goods_cat: "",
        // 价格
        goods_price: 0,
        // 数量
        goods_number: 0,
        // 重量
        goods_weight: 0,
        // 介绍
        goods_introduce: "",
        // 上传的图片临时路径（对象）
        pics: [],
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: [],
      },
      activeName: "0",
      goodsdata: [],
      // 动态参数
      manyParams: [],
      // 静态属性
      onlyParams: [],
      fileList: [],
    };
  },
  created() {
    this.getGoodsCateList();
  },
  methods: {
    async addGoodsOk() {
      this.addGoodsForm.goods_cat = this.checkedCatArr.join(",");
      // 第一步
      let dtParams = _.cloneDeep(this.manyParams);
      dtParams = dtParams.map((item) => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(","),
        };
      });
      // 第二步
      let jtParams = _.cloneDeep(this.onlyParams);
      jtParams = jtParams.map((item) => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals,
        };
      });
      // 第三步
      let mergeParams = [...dtParams, ...jtParams];
      // 第四步
      this.addGoodsForm.attrs = mergeParams;
      // 第五步
      let addGoodsForm = _.cloneDeep(this.addGoodsForm);
      await this.$API.addGoodsAPI(addGoodsForm);
      // 第六步
      this.$router.push("/goods");
    },
    // 上传图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
      const tmp_path = file.response.data.tmp_path;
      const index = this.addGoodsForm.pics.findIndex((item) => {
        return item.pic === tmp_path;
      });
      // 删除数组中的图片元素
      this.addGoodsForm.pics.splice(index,1);
    },
    // 删除图片时回调
    handlePreview() {},
    // 生成图片上传对象
    handleSuccess(res) {
      console.log("成功上传成功的回调", res);
      let PicObj = {
        pic: res.data.tmp_path,
      };
      this.addGoodsForm.pics.push(PicObj);
      console.log("要上传的数组", this.addGoodsForm.pics);
    },
    //监听tab切换之前
    beforeLeave(newActive, olActive) {
      console.log("newActive", newActive);
      console.log("olActive", olActive);
      if (olActive === "0" && this.checkedCatArr.length < 3) {
        this.message({
          message: "您必须选择完三级分类后，才能进行下一步的选择",
          type: "error",
        });
        return false;
      }
    },
    // 商品分类级联选择器改变时触发
    handleChange() {
      console.log("商品分类级联选择器改变时触发");
    },
    async handleClick() {
      console.log(this.activeName);
      console.log(this.currentCateId);
      if (this.activeName === "1") {
        console.log(this.currentCateId);
        // 渲染动态参数 传"many"
        const res = await this.$API.getGoodsParams(this.currentCateId, "many");
        // 将动态参数转换成数组
        console.log(res, 122222222);
        res.forEach((item) => {
          item.attr_vals = item.attr_vals.split(",");
        });
        console.log("获取动态的参数：", res);
        this.manyParams = res;
      } else if (this.activeName === "2") {
        // 渲染动态参数，传 only
        const res = await this.$API.getGoodsParams(this.currentCateId, "only");
        console.log("获取到的静态属性：", res);
        this.onlyParams = res;
      }
    },
    async getGoodsCateList() {
      const res = await this.$API.goodsAPI({ type: 3 });
      console.log("添加数据", res);
      this.goodsCatedata = res;
    },
  },
  computed: {
    currentCateId() {
      return this.checkedCatArr[this.checkedCatArr.length - 1];
    },
  },
};
</script>

<style lang="scss" scoped>
.el-row ::v-deep .el-step__title {
  font-size: 14px !important;
}
::v-deep .ql-container {
  height: 300px;
}
</style>